﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using Caliburn.Micro;
using OrbitOne.CRMLyncInfoDashboard.CRM;
using OrbitOne.CRMLyncInfoDashboard.CRM.OData;

namespace OrbitOne.CRMLyncInfoDashboard.SearchFieldProvisioner.ViewModels
{
    [Export(typeof(ISearchFieldProvisionerShellViewModel))]
    public class SearchFieldProvisionerShellViewModel : PropertyChangedBase,
        ISearchFieldProvisionerShellViewModel,
        ISearchFieldProvisionerDataCollection
    {
        //public const string InstallerUrl = "https://staging.orbitone.com/CrmLyncDashboardInstaller/OrbitOne.CRMLyncInfoDashboard.Setup.application";

        public const string InstallerUrl = "https://crmlync.orbitone.com/OrbitOne.CRMLyncInfoDashboard.Setup.application";
        private readonly ICrmDataProviderFactory m_crmDataProviderFactory;
        private readonly IClientScript m_clientScript;
        private List<string> m_statusMessages;


        public List<string> StatusMessages
        {
            get { return m_statusMessages; }
            set
            {
                m_statusMessages = value;
                base.NotifyOfPropertyChange(() => StatusMessages);
            }
        }

        [ImportingConstructor]
        public SearchFieldProvisionerShellViewModel(ICrmDataProviderFactory crmDataProviderFactory, 
            IClientScript clientScript)
        {
            m_crmDataProviderFactory = crmDataProviderFactory;
            m_clientScript = clientScript;
        }

        public void PopulateSearchField(object sender, RoutedEventArgs e)
        {
            StatusMessages = new List<string>();
            m_crmDataProviderFactory.CrmDataProviders
                .ToList()
                .ForEach(dp => dp.GetAllEntities(this));
        }

        public void GetInstallerClick(object sender, RoutedEventArgs e)
        {
            var serverUrl = m_clientScript.GetServerUrl();
            var installerWithParameters = string.Format("{0}?crmServerUrl={1}", InstallerUrl, serverUrl);
            HtmlPage.Window.Invoke("OpenUrl", installerWithParameters);
        }
    }
}